//
//  CZOauthViewController.swift
//  crkWeibo
//
//  Created by 陈荣科 on 15/12/19.
//  Copyright © 2015年 crk. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOauthViewController: UIViewController,UIWebViewDelegate {

    
    //MARK: - webViewDelegate的代理方法
    ///webView开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        //显示正在加载
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Gradient)
    }
    //webView加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    ///WebView是否要去加载一个网址，返回true加载，返回false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
     
        let url = request.URL!.absoluteString
        print("URL: \(url)")
        
        //当点击 不是授权或取消时，不会加载毁掉地址
        //直接加载
        if !url.hasPrefix(CZNetworkTool.sharedInstance.redirect_uri) {
            // 返回true去加载
            return true
        }
        
        //点击取消：http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        //点击授权：http://www.baidu.com/?code=742f5e452623ce9d9c172a5cc9ea4a26
        //获取url中?后面的内容：URL.query就是问号后面的东西
        if let query = request.URL?.query {
        
            //能到这里说明query有值
            let codeString = "code="///下面用这个string来取code=后面的东西
            
            //判断是否已code=开头
            if query.hasPrefix(codeString) {
                //string和nstring之间的转换不需要as？ as!
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
//                print("code:\(code)")
                
                //通过code获取AccessToken
                loadAccessToken(code)
            }else{
            
                self.close()
            }
        }else{
        
            print("query没有值")
        }
        
        return false
    }
    
    //控制器加载AccessToken
    func loadAccessToken(code:String) {
    
        //调用网络工具类加载AccessToken
        CZNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            
            //判断网络是否有错误
            if error != nil && result == nil{
                print("error: \(error)")
                
                SVProgressHUD.showInfoWithStatus("你的网络不给力")

                //延时1秒在关闭
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(),{ () -> Void in
                    //关闭授权
                    self.close()
                })
                
                return
            }
            //能到下面来就没有错，获取到了AccessToken
            //保存AccessToken
            //字典转模型
            let userAccount = CZUserAccount(dict: result!)
            
            
            userAccount.saveUserAccount()
            
            //切换到欢迎界面
           (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
            
            //关闭，登录页面
            self.close()
            
           
        }
    }
    
    //在这赋值的话，不需要添加约束，系统会自动添加约束
    //只有一个webView作为跟view并没有其他空间才可以在loadView中赋值
    override func loadView() {
        view = webView
        //监听webView加载网络地址
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载登录界面，url在CZNetworkTool中准备好了
        let url = CZNetworkTool.sharedInstance.oAuthURL()
        
//        print("url:\(url)")
        //发送请求
        let request = NSURLRequest(URL:url)
        
        webView.loadRequest(request)
        
        //添加填充 取消 按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.title = "登录"
    }
    
    
    //填充，调用函数
    func autoFill () {
    
        let js = "document.getElementById('userId').value='1373908320@qq.com'; document.getElementById('passwd').value='19921203crk/';"
        //让浏览器(webView)来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

    //取消带调用函数
    func close () {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK: - 懒加载
    private lazy var webView = UIWebView()
}
